package com.camin.android;

import com.camin.android.db.IngredientTable;
import com.camin.android.utils.Constants;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class IngredientRecipeActivity extends BaseActivity {
	
	TextView txtIngredientRecipe;
	EditText edtIngredientRecipeQty;
	Spinner spinnerIngredientRecipeUM;
	long ingredientId =-1l;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.ingredient_recipe);
        
		Button btnSelectIngredient = (Button) findViewById(R.id.btnSelectIngredient);
		btnSelectIngredient.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						IngredientListActivity.class);
				startActivityForResult(intent, 0);
			}
		});

        
		Button btnSaveIngredientRecipe = (Button) findViewById(R.id.btnSaveIngredientRecipe);
		btnSaveIngredientRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				long ingredientQty = new Long(edtIngredientRecipeQty.getText().toString());
				Intent data = new Intent();
				data.putExtra(Constants.INGREDIENT_ID, ingredientId);
				data.putExtra(Constants.INGREDIENT_QTY, ingredientQty);
				data.putExtra(Constants.INGREDIENT_UM, spinnerIngredientRecipeUM.getSelectedItem().toString());
				setResult(RESULT_OK, data);
				finish();
			}
		});

		txtIngredientRecipe = (TextView)findViewById(R.id.txtIngredientRecipe);
		edtIngredientRecipeQty = (EditText)findViewById(R.id.editIngredientRecipeQuantity);
		spinnerIngredientRecipeUM = (Spinner)findViewById(R.id.spinnerIngredientRecipeUM);
		
		Button btnCancelIngredientRecipe = (Button) findViewById(R.id.btnCancelIngredientRecipe);
		btnCancelIngredientRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
        
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK)
		{
			Bundle extras = data.getExtras();
			if (extras != null) {
				ingredientId = extras.getLong(Constants.INGREDIENT_ID, -1l);
			}
	        if (ingredientId != -1)	{
				Cursor cursor = getDataHelper().getIngredientById(getDatabase(), ingredientId);
				if (cursor.moveToFirst()) {
					txtIngredientRecipe.setText(cursor.getString(cursor
							.getColumnIndex(IngredientTable.ingredientName)));
				}
				getDatabase().close();
	        }
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
    
}
